package com.financing.wap.web.controller.api;



import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.financing.wap.common.Pager;
import com.financing.wap.common.ResultMap;
import com.financing.wap.common.ResultMap.STATUS;
import com.financing.wap.dto.ProductDetailPageDTO;
import com.financing.wap.dto.ProjectLikeDTO;
import com.financing.wap.service.IProductService;
import com.financing.wap.service.IProjectLikeService;
import com.financing.wap.util.DTOdateSetUtil;
import com.financing.wap.util.StringUtil;
import com.financing.wap.vo.ProjectLikeVO;
import com.financing.wap.vo.ProjectSubVO;
import com.financing.wap.web.controller.BaseController;

@Controller("projectLikeController")
@RequestMapping("/api/projectLike")
public class ProjectLikeController  extends BaseController{

	Logger logger = Logger.getLogger(getClass());

	@Autowired
	private IProjectLikeService projectLikeServiceImpl;
	
	@Autowired
	private IProductService projectServiceImpl;
	
	/**
	 * 展示收藏产品列表
	 * @return
	 */
	@RequestMapping("/list")
	@ResponseBody
	public ResultMap list(HttpServletRequest request, HttpServletResponse response,ProjectLikeDTO projectLikeDTO){
		ResultMap result = new ResultMap();
		try {
			//必须不能为空，需求改为要根据产品类型分类查询收藏的产品
			if(projectLikeDTO == null){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
				return result;
			}
			projectLikeDTO.setuId(getSession(true).getUser().getId());
			
			Pager pager = null;
			if(request.getParameter("pageNo") != null){
				pager = new Pager();
				pager.setPageNo(Integer.valueOf(request.getParameter("pageNo")));
				pager.setPageSize(Integer.valueOf(request.getParameter("pageSize")));
				pager.setTotalCount(projectLikeServiceImpl.countProjectLikeForFa(projectLikeDTO));
				result.setAttribute("pager", pager);
			}
			List<ProjectLikeVO> projectLikeDTOList = projectLikeServiceImpl.queryProjectLike(projectLikeDTO,pager);
			for(ProjectLikeVO projectLikeVo : projectLikeDTOList){
				ProductDetailPageDTO productDetailPageDTO = projectServiceImpl.getProductDetailView(projectLikeVo.getpId());
				projectLikeVo.setProductDetailPageDTO(productDetailPageDTO);
			}
			result.setAttribute("list", projectLikeDTOList);
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
		} catch (Exception e) {
			logger.info("project action error",e);
			result.setStatus(STATUS.WARN);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return  result;
	}

	/**
	 * 删除收藏产品
	 * @return
	 */
	@RequestMapping("/delete")
	@ResponseBody
	public ResultMap delete(HttpServletRequest request, HttpServletResponse response){

		ResultMap result = new ResultMap();
		try {
			String[] ids = request.getParameterValues("id");
			String pId=request.getParameter("pId");
			ProjectLikeDTO projectLikeDTO = new ProjectLikeDTO();
			projectLikeDTO.setuId(getSession(true).getUser().getId());
			if(ids!=null && ids.length>0){
				for(String id:ids){
					if(StringUtils.isNotBlank(pId)){
						projectLikeDTO.setpId(Integer.valueOf(pId));
					}
					projectLikeDTO.setId(Integer.valueOf(id));
					DTOdateSetUtil.setUpdateInfo(projectLikeDTO);
					projectLikeServiceImpl.deleteProjectLike(projectLikeDTO);
				}
			}else{
				if(StringUtils.isNotBlank(pId)){
					projectLikeDTO.setpId(Integer.valueOf(pId));
					DTOdateSetUtil.setUpdateInfo(projectLikeDTO);
					projectLikeServiceImpl.deleteProjectLike(projectLikeDTO);
				}
			}
			
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
		}catch(Exception e) {
			logger.error("==>warn messang:",e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}
	

	/**
	 * 添加收藏产品
	 * @return
	 */
	@RequestMapping(value="/add")
	@ResponseBody
	public ResultMap add(HttpServletRequest request, HttpServletResponse response, ProjectLikeDTO projectLikeDTO){

		ResultMap result = new ResultMap();
		try {
			projectLikeDTO.setuId(getSession(true).getUser().getId());
			
			List<ProjectLikeVO> projectLikeList = projectLikeServiceImpl.queryProjectLike(projectLikeDTO,null);
			
			if(projectLikeList != null && !projectLikeList.isEmpty()){
				result.setStatus(STATUS.ERROR);
				if(projectLikeDTO.getLikeType().intValue() == 2){
					result.setStatusCode(ResultMap.STATUS_CODE_PROJECT_SUB_EXIST);
				}else{
					result.setStatusCode(ResultMap.STATUS_CODE_PROJECT_LIKE_EXIST);
				}
			}else{

				DTOdateSetUtil.setUpdateInfo(projectLikeDTO);
				DTOdateSetUtil.setCreateInfo(projectLikeDTO);
				result.setAttribute("id", projectLikeServiceImpl.addProjectLike(projectLikeDTO));
				
				result.setStatus(STATUS.SUCCESS);
				result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			}
		}catch(Exception e) {
			logger.error("==>warn messang:",e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}
	
	/**
	 * 
	 * @Title: countAPI
	 * @Description: 产品收藏总数 
	 * @param @param productId
	 * @param @return   
	 * @return ResultMap   
	 * @throws
	 */
	@RequestMapping("/count")
	@ResponseBody
	public ResultMap countAPI(String productId){
		ResultMap result = new ResultMap();
		Map<String,Object> resultMap = new HashMap<String,Object>();
		try{
			String[] productIds = productId.split(",");
			for(String productIdTmp : productIds){
				resultMap.put(productIdTmp, projectLikeServiceImpl.countProjectLike(Integer.valueOf(productIdTmp)));
			}
			result.setAttribute("count",resultMap);
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
		}catch(Exception e){
			log.error("query count project like error!",e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}
	/**
	 * 订阅通知
	 * 查询订阅的产品信息
	 * @return
	 */
	@RequestMapping("/listSub")
	@ResponseBody
	public ResultMap listSub(HttpServletRequest request, HttpServletResponse response,ProjectLikeDTO projectLikeDTO){
		ResultMap result = new ResultMap();
		try {
			// 用户ID
			projectLikeDTO.setuId(getSession(true).getUser().getId());
			
			Pager pager = null;
			// 查询用户订阅的产品信息
			List<ProjectLikeVO> projectList = projectLikeServiceImpl.queryProjectSubForFa(projectLikeDTO.getuId());
			if(request.getParameter("pageNo") != null){
				pager = new Pager();
				pager.setPageNo(Integer.valueOf(request.getParameter("pageNo")));
				pager.setPageSize(Integer.valueOf(request.getParameter("pageSize")));
				int totalCout = 0;
				// 查询产品对应产品信息
				for (ProjectLikeVO tempProjectLikeDTO : projectList) {
					totalCout = totalCout + projectLikeServiceImpl.countProjectFlow (tempProjectLikeDTO.getpId());
				}
				pager.setTotalCount(totalCout);
				result.setAttribute("pager", pager);
				if(totalCout == 0){
					result.setAttribute("list", new ArrayList<ProjectSubVO>());
					result.setStatus(STATUS.SUCCESS);
					result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
					return result;
				}
			}
			// 查询订阅通知
			List<ProjectSubVO> projectSubVOList = projectLikeServiceImpl.queryProjectSubFlow(projectList, pager);
			result.setAttribute("list", projectSubVOList);
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
		} catch (Exception e) {
			logger.info("project action error",e);
			result.setStatus(STATUS.WARN);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return  result;
	}
	/**
	 * 产品信息
	 * @return
	 */
	@RequestMapping("/listAll")
	@ResponseBody
	public ResultMap listAll(HttpServletRequest request, HttpServletResponse response,ProjectLikeDTO projectLikeDTO){
		ResultMap result = new ResultMap();
		try {
			Pager pager = null;
			if(request.getParameter("pageNo") != null){
				pager = new Pager();
				pager.setPageNo(Integer.valueOf(request.getParameter("pageNo")));
				pager.setPageSize(Integer.valueOf(request.getParameter("pageSize")));
				int totalCout = 0;
				// 查询所有产品流水信息条数
				totalCout = projectLikeServiceImpl.countProjectFlow(null);
				pager.setTotalCount(totalCout);
				result.setAttribute("pager", pager);
				if(totalCout == 0){
					result.setAttribute("list", new ArrayList<ProjectLikeVO>());
					result.setStatus(STATUS.SUCCESS);
					result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
					return result;
				}
			}
			// 查询订阅通知
			List<ProjectLikeVO> projectList = new ArrayList<ProjectLikeVO>();
			List<ProjectSubVO> projectSubVOList = projectLikeServiceImpl.queryProjectSubFlow(projectList, pager);
			result.setAttribute("list", projectSubVOList);
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
		} catch (Exception e) {
			logger.info("project action error",e);
			result.setStatus(STATUS.WARN);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return  result;
	}
	/**
	 * 产品信息\订阅通知 详情接口
	 * @return
	 */
	@RequestMapping("/productInfo")
	@ResponseBody
	public ResultMap productInfo(HttpServletRequest request, HttpServletResponse response,ProjectLikeDTO projectLikeDTO){
		ResultMap result = new ResultMap();
		try {
			Map<String, Object> temMap = new HashMap<String, Object>();
			temMap.put("id", projectLikeDTO.getId());
			ProjectSubVO ProjectSubVO = projectLikeServiceImpl.queryProjectFlowById(temMap);
			ProjectSubVO.setContent(this.packgeProductInfo(ProjectSubVO));
			result.setAttribute("pricectLike", ProjectSubVO);
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
		} catch (Exception e) {
			logger.info("project action error",e);
			result.setStatus(STATUS.WARN);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return  result;
	}
	private String packgeProductInfo(ProjectSubVO ProjectSubVO){
		StringBuffer contentBuffer = new StringBuffer();
		contentBuffer.append("【");
		contentBuffer.append(ProjectSubVO.getpName());
		contentBuffer.append("】");
		if("1".equals(ProjectSubVO.getNoticeType())){
			contentBuffer.append("正式上线了，欢迎您来预约，预约热线400-855-8085；");
		}else if("2".equals(ProjectSubVO.getNoticeType())){
			contentBuffer.append("，整体规模【");
			contentBuffer.append(StringUtil.ObjPrice2Wan(ProjectSubVO.getpExpectSubscriptionAmount().intValue()));
			contentBuffer.append("万】，当前募集【");
			contentBuffer.append(StringUtil.ObjPrice2Wan(ProjectSubVO.getpAllSubscriptionAmount().intValue()));
			contentBuffer.append("万】，募集进度为【");
			contentBuffer.append(ProjectSubVO.getpAllSubscriptionAmount().divide(ProjectSubVO.getpExpectSubscriptionAmount(), 2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)).intValue());
			contentBuffer.append("%】。");
		}else if("3".equals(ProjectSubVO.getNoticeType())){
			contentBuffer.append("，整体规模【");
			contentBuffer.append(StringUtil.ObjPrice2Wan(ProjectSubVO.getpExpectSubscriptionAmount().intValue()));
			contentBuffer.append("万】，当前已经募集完成，产品成立。");
		}
		return contentBuffer.toString();
	}
}
